<template>
    <div class="content">
        <div>{{ definitionNm ? definitionNm + '-审批详情' : '审批详情' }}</div>
        <el-divider />
        <div class="business">
            <el-form :disabled="disableFlag" :model="form" label-position="top" label-width="auto" :inline="true"
                v-loading="loading" element-loading-text="数据加载中...">
                <el-form-item :label="item.fieldCnNm" v-for="item in formData" :key="item.id"
                    :style="(item.fieldType === '1' || item.fieldType === '6' || item.fieldType === '7'
                        || item.fieldType === '9' || item.fieldType === '10' || item.fieldType === '11') ? 'width: 100%;' : ''">
                    <el-input clearable :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]"
                        style="width: 200px" v-if="item.fieldType === '0'" />
                    <el-input :disabled="item.modifyFlag === '1'" type="textarea" v-model="form[item.fieldEnNm]"
                        v-else-if="item.fieldType === '1'" :rows="4" />
                    <el-input clearable :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]"
                        style="width: 200px" v-if="item.fieldType === '2'">
                        <template #append>
                            {{ item.fieldConf }}
                        </template>
                    </el-input>
                    <el-date-picker :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]" type="date"
                        format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 200px"
                        v-else-if="item.fieldType === '3'" />
                    <el-time-picker :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]" format="HH:mm:ss"
                        value-format="HH:mm:ss" style="width: 200px" v-else-if="item.fieldType === '4'" />
                    <el-date-picker :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]" type="datetime"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 200px"
                        v-else-if="item.fieldType === '5'" />
                    <div v-else-if="item.fieldType === '6'">
                        <el-upload :disabled="item.modifyFlag === '1'" v-model:file-list="item.pictureList"
                            :class="{ disableUpload: item.pictureList.length > 2 }"
                            :before-upload="(uploadFile) => beforeAvatarUpload(uploadFile, true)" :headers="header"
                            :action="action" :on-preview="(uploadFile) => handlePictureCardPreview(uploadFile, item.id)"
                            :on-remove="(uploadFile, uploadFiles) => handleRemove(uploadFile, uploadFiles, item.fieldEnNm)"
                            :on-success="(response, uploadFile, uploadFiles) => handleAvatarSuccess(response, uploadFile, uploadFiles, item.fieldEnNm)"
                            list-type="picture-card" :limit="3">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                        <el-dialog v-model="item.dialogVisible">
                            <img style="height: 100%; width: 100%;" w-full :src="item.dialogImageUrl"
                                alt="Preview Image" />
                        </el-dialog>
                    </div>
                    <el-upload :disabled="item.modifyFlag === '1'" v-model:file-list="item.fileList" :headers="header"
                        :action="action" multiple :limit="1"
                        :before-upload="(uploadFile) => beforeAvatarUpload(uploadFile, false)"
                        :on-remove="(uploadFile, uploadFiles) => handleRemove(uploadFile, uploadFiles, item.fieldEnNm)"
                        :on-success="(response, uploadFile, uploadFiles) => handleAvatarSuccess(response, uploadFile, uploadFiles, item.fieldEnNm)"
                        :on-preview="handlePreview" v-else-if="item.fieldType === '7'">
                        <el-button type="primary" plain :disabled="item.fileList.length > 0">点击上传</el-button>
                    </el-upload>
                    <el-select :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]" clearable
                        style="width: 200px" v-else-if="item.fieldType === '8'">
                        <el-option v-for="dictItem in item.options" :key="dictItem.code" :label="dictItem.value"
                            :value="dictItem.code" />
                    </el-select>
                    <el-radio-group :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]"
                        v-else-if="item.fieldType === '9'">
                        <el-radio v-for="dictItem in item.options" :value="dictItem.code">
                            {{ dictItem.value }}
                        </el-radio>
                    </el-radio-group>
                    <el-rate :disabled="item.modifyFlag === '1'" v-model="form[item.fieldEnNm]"
                        v-else-if="item.fieldType === '10'" />
                    <div class="table" style="max-width:90vw" v-else-if="item.fieldType === '11'">
                        <el-table border empty-text="暂无数据" :data="form[item.fieldEnNm]"
                            :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }">
                            <el-table-column :prop="tableField.fieldEnNm" :label="tableField.fieldCnNm" min-width="150"
                                v-for="tableField in item.tableFields" :key="tableField.id">
                                <template #default="{ row }">
                                    <el-input size="small" clearable v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'"
                                        :placeholder="'请输入' + tableField.fieldCnNm"
                                        v-if="tableField.fieldType === '0'" />
                                    <el-input size="small" clearable v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'"
                                        :placeholder="'请输入' + tableField.fieldCnNm" v-if="tableField.fieldType === '2'">
                                        <template #append>
                                            {{ tableField.fieldConf }}
                                        </template>
                                    </el-input>
                                    <el-date-picker size="small" v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'" type="date"
                                        :placeholder="'请选择' + tableField.fieldCnNm" format="YYYY-MM-DD"
                                        value-format="YYYY-MM-DD" v-else-if="tableField.fieldType === '3'"
                                        style="width: 125px" />
                                    <el-time-picker size="small" v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'"
                                        :placeholder="'请选择' + tableField.fieldCnNm" format="HH:mm:ss"
                                        value-format="HH:mm:ss" v-else-if="tableField.fieldType === '4'"
                                        style="width: 125px" />
                                    <el-date-picker size="small" v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'" type="datetime"
                                        :placeholder="'请选择' + tableField.fieldCnNm" format="YYYY-MM-DD HH:mm:ss"
                                        value-format="YYYY-MM-DD HH:mm:ss" v-else-if="tableField.fieldType === '5'"
                                        style="width: 125px" />
                                    <el-select size="small" v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'" clearable
                                        :placeholder="'请选择' + tableField.fieldCnNm"
                                        v-else-if="tableField.fieldType === '8'">
                                        <el-option v-for="dictItem in tableField.options" :key="dictItem.code"
                                            :label="dictItem.value" :value="dictItem.code" />
                                    </el-select>
                                    <el-radio-group size="small" v-model="row[tableField.fieldEnNm]"
                                        :disabled="tableField.modifyFlag === '1'"
                                        v-else-if="tableField.fieldType === '9'">
                                        <el-radio v-for="dictItem in tableField.options" :value="dictItem.code">{{
                                            dictItem.value }}</el-radio>
                                    </el-radio-group>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-form-item>
            </el-form>
        </div>
        <el-divider />
        <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="审批节点处理人" name="0">
                <div class="table">
                    <el-table empty-text="暂无数据" row-key="id" default-expand-all :show-overflow-tooltip="true"
                        :data="tableData" v-loading="loading" element-loading-text="数据加载中..."
                        :header-cell-style="{ background: 'var(--table-title-color)', color: 'var(--table-title-font-color)' }">
                        <el-table-column prop="assignee" label="处理人">
                            <template #default="{ row }">
                                <span>{{ row.assignee }}</span>
                                <span v-if="row.relateAssignee">
                                    <span v-if="row.taskType === '1'">{{ '(' + row.relateAssignee + '转办)' }}</span>
                                    <span v-if="row.taskType === '2'">{{ '(' + row.relateAssignee + '加签)' }}</span>
                                </span>
                                <span style="margin-left: 5px; font-size: 12px; color: #409EFF;">
                                    {{ row.ccTos ? '抄送:' + row.ccTos : '' }}
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="status" label="处理状态">
                            <template #default="scope">
                                <span v-if="scope.row.status === '-1'">
                                    <el-tag type="info">发起审批</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '0'">
                                    <el-tag type="primary">等待处理</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '1'">
                                    <el-tag type="success">已同意</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '2'">
                                    <el-tag type="danger">已拒绝</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '3'">
                                    <el-tag type="warning">已退回</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '4'">
                                    <el-tag type="info">发起人已撤销</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '5'">
                                    <el-tag type="info">转办给他人</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '6'">
                                    <el-tag type="info">重新发起审批</el-tag>
                                </span>
                                <span v-else-if="scope.row.status === '7'">
                                    <el-tag type="info">作废</el-tag>
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="operationTime" label="处理时间" />
                        <el-table-column prop="remark" label="处理意见" />
                    </el-table>
                </div>
            </el-tab-pane>
            <el-tab-pane label="审批节点配置" name="1">
                <div>
                    <processDesign :init-data="node" :disabled="true"></processDesign>
                </div>
            </el-tab-pane>
        </el-tabs>
        <div class="button">
            <el-button type="success" @click="submit('1')" :size="$isMobile() ? 'small' : ''"
                v-if="!disableFlag && operationButton.includes('0')">同意</el-button>
            <el-button type="danger" @click="submit('2')" :size="$isMobile() ? 'small' : ''"
                v-if="!disableFlag && operationButton.includes('1')">拒绝</el-button>
            <el-button type="warning" @click="submit('3')" :size="$isMobile() ? 'small' : ''"
                v-if="!disableFlag && operationButton.includes('2')">退回</el-button>
            <el-button type="primary" @click="submit('5')" :size="$isMobile() ? 'small' : ''"
                v-if="!disableFlag && operationButton.includes('3')">转办</el-button>
            <el-button type="info" @click="submit('6')" :size="$isMobile() ? 'small' : ''"
                v-if="!disableFlag && operationButton.includes('4')">加签</el-button>
            <el-button @click="router.back()" :size="$isMobile() ? 'small' : ''">返回</el-button>
        </div>
        <workflowSubmit ref="wf" @serversUpdated="init"></workflowSubmit>
        <div class="seal" v-if="instanceStatus !== '0'">
            <workflowSeal :status="instanceStatus"></workflowSeal>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from "vue-router";
import api from "@/api"
import { Decrypt } from '@/utils/secret.js'
import workflowSubmit from "./workflowSubmit.vue";
import workflowSeal from "./workflowSeal.vue"
import processDesign from "../config/processDesign.vue";


const loading = ref(true)
const route = useRoute();
const router = useRouter();
const instanceId = ref()
const taskId = ref()
const definitionNm = ref()
const action = ref(import.meta.env.VITE_BASE_URL + '/system/file/upload?business=审批文件上传')
const header = ref()
const form = ref({})
const formData = ref([])
const tableData = ref([])
const modifyData = ref([])
const disableFlag = ref(true)
const operationButton = ref('')
const wf = ref()
const instanceStatus = ref('0')
const activeName = ref('0')
const node = ref()

//初始化
const init = async () => {
    loading.value = true
    disableFlag.value = true
    await getBusinessData(instanceId.value)
    await getTaskNodeList(instanceId.value)
    await getInstanceStatus(instanceId.value)
    loading.value = false
}

const getBusinessData = async (instanceId) => {
    const res = await api.post('/workflow/dataDetail', { instanceId })
    if (res.data.code === 200) {
        const data = res.data.data
        const dataEveryItem = async (item) => {
            form.value[item.fieldEnNm] = item.value
            //处理图片
            if (item.fieldType === '6') {
                item.pictureList = []
                item.dialogImageUrl = ''
                item.dialogVisible = false
                if (item.value) {
                    const valueArr = item.value.split(",");
                    valueArr.forEach(valueItem => {
                        item.pictureList.push(
                            {
                                name: decodeURIComponent(escape(atob(valueItem))),
                                response: {
                                    data: valueItem
                                },
                                url: import.meta.env.VITE_BASE_URL + '/system/file/download/' + valueItem
                            }
                        )
                    })
                }
                //处理文件
            } else if (item.fieldType === '7') {
                item.fileList = []
                if (item.value) {
                    const valueArr = item.value.split(",");
                    valueArr.forEach(valueItem => {
                        item.fileList.push(
                            {
                                name: decodeURIComponent(escape(atob(valueItem))),
                                response: {
                                    data: valueItem
                                },
                                url: import.meta.env.VITE_BASE_URL + '/system/file/download/' + valueItem
                            })
                    })
                }
            } else if (item.fieldType === '8' || item.fieldType === '9') {
                item.options = await getDict(item.fieldConf)
            } else if (item.fieldType === '11') {
                for (const tableField of item.tableFields) {
                    if (tableField.fieldType === '8' || tableField.fieldType === '9') {
                        tableField.options = await getDict(tableField.fieldConf)
                    }
                }
            }
            if (item.modifyFlag === '0') {
                modifyData.value.push(item)
            }
        }
        const dealAll = async () => {
            return await Promise.all(data.map(async item => {
                await dataEveryItem(item)
                return item
            }))
        }
        formData.value = await dealAll()
    } else {
        ElMessage.error(res.data.msg)
    }
}

const getTaskNodeList = async (instanceId) => {
    const res = await api.post('/workflow/taskInstance/taskNodeList', { instanceId })
    if (res.data.code === 200) {
        const data = res.data.data
        tableData.value = data
        //判断待处理节点的处理人是否为当前登录人如果是则展示处理按钮
        if (data && data.length > 0) {
            const taskNode = data[0]
            const userStr = window.localStorage.getItem("access-admin")
            const userId = JSON.parse(userStr).userId
            if (taskId.value) {
                if (taskNode.assigneeId === userId && taskNode.status === '0') {
                    disableFlag.value = false
                } else if (taskNode.children) {
                    const assigneeTaskNode = taskNode.children.find(item => item.assigneeId === userId && item.status === '0')
                    if (assigneeTaskNode) {
                        disableFlag.value = false
                    }
                }
            }
        }
    } else {
        ElMessage.error(res.data.msg)
    }
}


const getInstanceStatus = async (instanceId) => {
    const res = await api.post('/workflow/instance/getProcessInfo', { id: instanceId })
    if (res.data.code === 200) {
        const data = res.data.data
        instanceStatus.value = data.instanceStatus
        if (data.operationButton) {
            operationButton.value = data.operationButton
        }
    } else {
        ElMessage.error(res.data.msg)
    }
}

const beforeAvatarUpload = (uploadFile, type) => {
    if (type) {
        const isJPG = (uploadFile.type === 'image/jpeg') || (uploadFile.type === 'image/png');
        if (!isJPG) {
            ElMessage.error('上传图片只能是JPG/PNG格式!');
            return false;
        }
    }
    const isLt5M = uploadFile.size / 1024 / 1024 < 5;
    if (!isLt5M) {
        ElMessage.error('上传文件大小不能超过5MB!');
        return false;
    }
    return true
}

const handlePictureCardPreview = (uploadFile, id) => {
    formData.value.forEach(item => {
        if (item.id === id) {
            item.dialogImageUrl = uploadFile.url
            item.dialogVisible = true
        }
    })
}

const handleRemove = (uploadFile, uploadFiles, fieldEnNm) => {
    const value = uploadFiles.map(item => item.response.data).join(',');
    console.log(value)
    form.value[fieldEnNm] = value
}

const handleAvatarSuccess = (res, uploadFile, uploadFiles, fieldEnNm) => {
    if (res.code === 200) {
        const value = uploadFiles.map(item => item.response.data).join(',');
        console.log(value)
        form.value[fieldEnNm] = value
    } else {
        uploadFiles.pop()
        ElMessage.error(res.msg)
    }
}

const handlePreview = (file) => {
    console.log(file)
    var a = document.createElement('a')
    a.download = file.name
    a.href = import.meta.env.VITE_BASE_URL + '/system/file/download/' + file.response.data
    a.click()
    window.URL.revokeObjectURL(a.href)
}

const submit = (approvalStatus) => {
    //判断页面数据是否有变化，变化了需要提交变化后的数据
    let flag = false
    modifyData.value.forEach(item => {
        if (form.value[item.fieldEnNm] != item.value) {
            flag = true
        }
    })
    if (flag) {
        wf.value.initCommit(taskId.value, instanceId.value, approvalStatus, form.value)
    } else {
        wf.value.initCommit(taskId.value, instanceId.value, approvalStatus, null)
    }
}

const getDict = async (dictCode) => {
    const res = await api.get('/system/dict/getDictItems', { dictCode })
    if (res.data.code === 200) {
        return res.data.data
    } else {
        ElMessage.error(res.data.msg)
        return null
    }
}

const handleClick = (tab) => {
    activeName.value = tab.props.name
    if (activeName.value === '1' && !node.value) {
        getNodeInfo()
    }
}

const getNodeInfo = async () => {
    const res = await api.post('/workflow/instance/getNodeInfo', { id: instanceId.value })
    if (res.data.code === 200) {
        node.value = res.data.data
    } else {
        ElMessage.error(res.data.msg)
    }
}

onMounted(() => {
    const str = window.localStorage.getItem("access-admin")
    const user = JSON.parse(str)
    const token = Decrypt(user.token)
    header.value = { token: token, accessAuthor: 'allow' }
    if (route.query.instanceId) {
        instanceId.value = route.query.instanceId
    }
    if (route.query.taskId) {
        taskId.value = route.query.taskId
    }
    if (route.query.definitionNm) {
        definitionNm.value = route.query.definitionNm
    }
    init()
})
</script>
<style scoped lang="less">
.business {
    min-height: 40vh;
}

.button {
    height: 100px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.content {
    position: relative;
}

.seal {
    position: absolute;
    right: 50px;
    top: 50px;
    z-index: 1;
}
</style>